<template>
  <div class="form-my-published-task" style="position: relative">
    <el-form
      ref="flowMyStartedTask"
      :model="formFilter"
      label-width="75px"
      :size="layoutStore.defaultFormItemSize"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFlowMyStartedTask(true)" @reset="onReset">
        <el-form-item label="所属流程">
          <el-select
            class="filter-item"
            v-model="formFilter.entryId"
            :clearable="true"
            placeholder="所属流程"
            @visible-change="entryIdWidget.onVisibleChange"
          >
            <el-option
              v-for="item in entryIdWidget.dropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="流程状态" prop="flowStatus">
          <el-select
            class="filter-item"
            v-model="formFilter.flowStatus"
            :clearable="true"
            placeholder="流程状态"
          >
            <el-option
              v-for="item in SysFlowWorkOrderStatus.getList()"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发起时间" prop="createTime">
          <date-range
            class="filter-item"
            v-model="formFilter.createTime"
            :clearable="true"
            :allowTypes="['day']"
            align="left"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="工单编号" prop="workOrderCode">
          <el-input
            class="filter-item"
            v-model="formFilter.workOrderCode"
            :clearable="true"
            placeholder="工单编号"
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <div class="table-box">
      <table-box
        class="page-table"
        style="padding: 0"
        :data="flowMyStartedTaskWidget.dataList"
        :size="layoutStore.defaultFormItemSize"
        @sort-change="flowMyStartedTaskWidget.onSortChange"
        @refresh="refreshFlowMyStartedTask(true)"
        :seq-config="{
          startIndex: (flowMyStartedTaskWidget.currentPage - 1) * flowMyStartedTaskWidget.pageSize,
        }"
        :hasExtend="true"
      >
        <template v-slot:operator>
          <el-button
            type="primary"
            :icon="Plus"
            :size="layoutStore.defaultFormItemSize"
            @click="onStartFlow()"
          >
            发起流程
          </el-button>
        </template>
        <vxe-column
          title="序号"
          type="seq"
          width="55px"
          :index="flowMyStartedTaskWidget.getTableIndex"
        />
        <vxe-column title="工单编号" show-overflow="tooltip" field="workOrderCode" :width="200" />
        <vxe-column title="所属流程" field="processDefinitionName" />
        <vxe-column title="流程标题" field="summaryData" />
        <vxe-column title="发起时间" field="createTime" :width="180" />
        <vxe-column title="审批节点" field="runtimeTaskInfo.taskName" />
        <vxe-column title="流程状态" field="flowStatusShowName" />
        <vxe-column title="操作" :width="180" fixed="right" :show-overflow="false">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :size="layoutStore.defaultFormItemSize"
              @click.stop="onViewWorkOrder(row)"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              link
              :size="layoutStore.defaultFormItemSize"
              :disabled="row.flowStatus === SysFlowWorkOrderStatus.CANCEL"
              @click.stop="onHandlerRemindClick(row)"
            >
              催办
            </el-button>
            <el-button
              type="primary"
              link
              :size="layoutStore.defaultFormItemSize"
              :disabled="row.flowStatus === SysFlowWorkOrderStatus.CANCEL"
              @click.stop="onCancelWorkOrder(row)"
            >
              撤销
            </el-button>
          </template>
        </vxe-column>
        <template #pagination>
          <el-row type="flex" justify="end" style="margin-top: 16px">
            <el-pagination
              :total="flowMyStartedTaskWidget.totalCount"
              :current-page="flowMyStartedTaskWidget.currentPage"
              :page-size="flowMyStartedTaskWidget.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, prev, pager, next, sizes"
              @current-change="flowMyStartedTaskWidget.onCurrentPageChange"
              @size-change="flowMyStartedTaskWidget.onPageSizeChange"
            >
            </el-pagination>
          </el-row>
        </template>
      </table-box>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import { FlowOperationController, FlowEntryController } from '@/api/flow';
import { useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { TableOptions } from '@/common/types/pagination';
import { ANY_OBJECT } from '@/types/generic';
import { DropdownOptions, ListData } from '@/common/types/list';
import { DictData } from '@/common/staticDict/types';
import { getAppId, getToken } from '@/common/utils';
import {
  SysFlowTaskOperationType,
  SysFlowTaskType,
  SysFlowWorkOrderStatus,
} from '@/common/staticDict/flow';
import { useLayoutStore } from '@/store';

const layoutStore = useLayoutStore();
const { Plus, useDropdown, useTable, Dialog } = useCommon();
const router = useRouter();

const formFilter = ref({
  entryId: undefined,
  createTime: [],
  workOrderCode: undefined,
  flowStatus: undefined,
});

const flowMyStartedTask = ref();

const tabChange = () => {
  nextTick(() => {
    refreshFlowMyStartedTask(true);
  });
};

const onReset = () => {
  if (flowMyStartedTask.value) flowMyStartedTask.value.resetFields();
  refreshFlowMyStartedTask(true);
};

const loadEntryIdDropdownData = () => {
  return new Promise((resolve, reject) => {
    FlowEntryController.listDict()
      .then(res => {
        resolve({
          dataList: res.data,
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};

const loadTableData = params => {
  return new Promise((resolve, reject) => {
    if (params == null) params = {};
    params = {
      ...params,
      entryId: formFilter.value.entryId,
      flowWorkOrderDtoFilter: {
        workOrderCode: formFilter.value.workOrderCode,
        flowStatus: formFilter.value.flowStatus,
        createTimeStart: Array.isArray(formFilter.value.createTime)
          ? formFilter.value.createTime[0]
          : undefined,
        createTimeEnd: Array.isArray(formFilter.value.createTime)
          ? formFilter.value.createTime[1]
          : undefined,
      },
    };

    FlowOperationController.listAllMyWorkOrder(params)
      .then(res => {
        res.data.dataList = res.data.dataList.map(item => {
          let initTaskInfo = item.initTaskInfo == null ? {} : JSON.parse(item.initTaskInfo);
          let runtimeTaskInfo =
            Array.isArray(item.runtimeTaskInfoList) && item.runtimeTaskInfoList.length > 0
              ? item.runtimeTaskInfoList[0]
              : {};
          return {
            ...item,
            flowStatusShowName: SysFlowWorkOrderStatus.getValue(item.flowStatus),
            initTaskInfo,
            runtimeTaskInfo,
          };
        });
        resolve({
          dataList: res.data.dataList,
          totalCount: res.data.totalCount,
        });
      })
      .catch(e => {
        console.log(e);
        reject(e);
      });
  });
};

const loadTableDataVerify = () => {
  return true;
};

const dropdownOptions: DropdownOptions<ANY_OBJECT> = {
  loadData: loadEntryIdDropdownData,
};
const tableOptions: TableOptions<ANY_OBJECT> = {
  loadTableData: loadTableData,
  verifyTableParameter: loadTableDataVerify,
  paged: true,
};

const entryIdWidget = reactive(useDropdown(dropdownOptions));
const flowMyStartedTaskWidget = reactive(useTable(tableOptions));

const refreshFlowMyStartedTask = (reloadData = false) => {
  if (reloadData) {
    flowMyStartedTaskWidget.refreshTable(true, 1);
  } else {
    flowMyStartedTaskWidget.refreshTable();
  }
};

const onStartFlow = () => {
  router.push({
    name: getAppId() == null || getAppId() === '' ? 'formAllStartTask' : 'thridFormAllStartTask',
    query: {
      appId: getAppId(),
      token: getToken(),
    },
  });
};

const onViewWorkOrder = row => {
  let params = {
    processInstanceId: row.processInstanceId,
    // 草稿传入taskId
    taskId:
      row.flowStatus === SysFlowWorkOrderStatus.DRAFT ? row.runtimeTaskInfo.taskId : undefined,
  };

  FlowOperationController.viewInitialHistoricTaskInfo(params)
    .then(res => {
      if (res.data) {
        router.push({
          name: res.data.routerName || 'handlerFlowTask',
          query: {
            isRuntime: false,
            processDefinitionKey: row.processDefinitionKey,
            processInstanceId: row.processInstanceId,
            processDefinitionId: row.processDefinitionId,
            formId: res.data.formId,
            routerName: res.data.routerName,
            readOnly: true,
            taskId: row.runtimeTaskInfo.taskId,
            flowEntryName: row.processDefinitionName,
            processInstanceInitiator: row.processInstanceInitiator,
          },
        });
      }
    })
    .catch(e => {
      console.log(e);
    });
};

const onHandlerRemindClick = row => {
  FlowOperationController.remindRuntimeTask({
    workOrderId: row.workOrderId,
  })
    .then(res => {
      ElMessage.success('催办成功');
    })
    .catch(e => {
      console.log(e);
    });
};

const onCancelWorkOrder = row => {
  ElMessageBox.confirm('是否撤销此工单？', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(res => {
      let params = {
        workOrderId: row.workOrderId,
        cancelReason: '主动撤销',
      };

      FlowOperationController.cancelWorkOrder(params)
        .then(res => {
          ElMessage.success('撤销成功！');
          refreshFlowMyStartedTask();
        })
        .catch(e => {
          console.log(e);
        });
    })
    .catch(e => {
      //
    });
};

onMounted(() => {
  refreshFlowMyStartedTask(true);
});

onActivated(() => {
  refreshFlowMyStartedTask(true);
});
</script>

<style scoped>
.table-box {
  display: flex;
  flex-direction: column;
  background: white;
  flex: 1;
  padding: 16px 24px;
}
</style>
